package com.bristua.mall.user.biz;

import com.bristua.mall.common.enums.CommonCode;
import com.bristua.mall.common.exception.BizException;
import com.bristua.mall.common.utils.CacheUtil;
import com.bristua.mall.common.utils.DateUtil;
import com.bristua.mall.common.utils.SequenceUtil;
import com.bristua.mall.user.dao.TUserMapper;
import com.bristua.mall.user.enums.UserCode;
import com.bristua.mall.user.model.TUser;
import com.bristua.mall.user.model.condition.TUserExample;
import com.bristua.mall.user.model.condition.userReg.UserReg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2019/3/30.
 */
@Service
public class UserLoginBiz {

    @Resource
    private TUserMapper tUserMapper;

    @Autowired
    private UserRegBiz userRegBiz;

    @Autowired
    private CacheUtil cacheUtil;

    public String userLogin(UserReg userReg){
        if(!StringUtils.isEmpty(userReg.getPhone())){
            TUser tUser = queryUserByPhone(userReg.getPhone());
            if(tUser!=null){
                return cacheUtil.put(tUser.getPhone(), tUser);
            }
            userRegBiz.userReg(userReg);
            return userLogin(userReg);
        }
        throw new BizException(CommonCode.LOGIN_FAIL.getCode(),CommonCode.LOGIN_FAIL.getMsg());
    }

    public TUser queryUserByPhone(String phone){
        TUserExample tUserExample = new TUserExample();
        tUserExample.createCriteria().andPhoneEqualTo(phone);
        List<TUser> tUsers = tUserMapper.selectByExample(tUserExample);
        if(tUsers!=null && tUsers.size()>0){
           return tUsers.get(0);
        }
        return null;
    }
}
